<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Your app title</title>
<link href="/customer_plat/public/stylesheets/webix_3.0.4.css"
	rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css"
	href="http://cdn.bootcss.com/font-awesome/4.4.0/css/font-awesome.css">
<link rel="stylesheet" type="text/css"
	href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.css">
<link href="/customer_plat/public/stylesheets/app.css" rel="stylesheet">
<script src="/customer_plat/public/javascripts/jquery.min.js"></script>
<script src="/customer_plat/public/javascripts/webix_3.0.4.js"
	type="text/javascript" charset="utf-8"></script>
<script src="/customer_plat/public/javascripts/vue.min.js"></script>
<script type="text/javascript">
	webix.ready(function() {
				var my_templaet = {
					template : "<span style='font-size:20px; font-weight:bold; color:#3498DB'; >每日各项目、工序用量明细表</span>&nbsp;/&nbsp;&nbsp;CutterUseRecord",
					height : 45,
					borderless : true
				};
				var my_toolbar = {
					view : "toolbar",
					elements : [ {
						view : "datepicker",
						id : "sel_date",
						timepicker : true,
						label : "日期",
						labelAlign : "right",
						name : "end",
						stringResult : true,
						format : "%Y-%m-%d",
						width : 240
					},  {
						view : "button",
						value : "查询",
						width : 100,
						click : "select"
					} ]
				};
				var body = new webix.ui({
					container : "body",
					type : "line",
					id : "mylayout",
					rows : [ my_templaet, my_toolbar ],// ----rows结束----
				//----rows结束----
				});// ---webix.ui结束-
			});
</script>
</head>
<body style="background-color: #fff;">
	<div style="height: 45px; margin-top: 20px; margin-left: 5px;">
		<div id="body"></div>
		<div id="app" style="height: 800px;overflow-y:scroll;">
			<div class='d-panel'>
				<table class="table table-striped table-bordered" id="tableExcel" style="border: 1px solid;" border="1">
					<tr v-for="list in prolist" track-by="$index">
						<td><a @click="showdetail(list,$index)">{{list}}</a>
							<div class='d-panel' id="proc" style="display: none">
								<table class="table table-striped table-bordered">
									<tr v-for="list in numlist" track-by="$index">
										<td style="white-space:nowrap; word-break:  keep-all; width: 400px;">{{list.cutter_specs}}</td>
										<td>{{list.pr}}</td>
										<td v-for="col in columns" track-by="$index">{{list[col]}}</td>
									<tr>
								</table>
										<div class="btn btn-success" @click="outputexcel" style="float:right">
          					  导出</div>
       						 </div>
							</div></td>
							 
					</tr>
				</table>
		 
				<div></div>
			</div>
		</div>
	</div>
	<script type="text/javascript">
 var prolist = [];
 var procelist = [];
 var spceslist = [];
 var numlist = [];
 var numobj = {};
 var columns=[];
 var jsonlist =[]; //report.demodata.data;

function sortByKey(array, key) {
  return array.sort(function(a, b) {
     var x = a[key]; var y = b[key];
     return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  });
}

function guid() {
  function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }
  return [s4(), s4(), "-", s4(), "-", s4(), "-", s4(), "-", s4(), s4(), s4()].join("");
}

function getSessionId() {
  var id = sessionStorage.getItem('session_id');
  if (!id) {
    id = guid();
    sessionStorage.setItem('session_id', id);
  }
  return id;
}

 function apiCall(method, path, params, cb) {
	$.ajax({
		url: path,
		method: method,
		cache: false,
		data: params,
		success: function(data) {
			cb(data);
		},
		error: function(xhr, status, data) {
			cb(jQuery.parseJSON(xhr.responseText));
		}
	});
}

function init() {
	var url = "@{record.RecordAction.getCutterUseProjectRecordInfo}";
	var params = {};
	var date = $$("sel_date").getValue();
	params["date"] = date.substring(0,10);
 	 apiCall('GET',url,params,function(data){
     jsonlist=data;
     console.log(jsonlist)
     jsonlist.forEach(function(item,index) {
      if (prolist.indexOf(jsonlist[index].project_name) === -1) {
       prolist.push(jsonlist[index].project_name);
      }
    })
  })
};   

function fillTable(newarr){
  newarr.forEach(function(item,index){
    numobj = {}
    numobj.cutter_specs = item.cutter_specs;
     
    if(item.type === 1) {
      numobj.pr = '计划数量';
    } else {
      numobj.pr = '真实数量';
    }
    procelist.forEach(function(proce,index) {
      if (item.process_name === proce) 
        numobj['col'+index] = item.num ;
      else numobj['col'+index] ='';
    }); 
   numlist.push(numobj)
 });
}

function clcSum(procelist,numlist){
  var numobj1 = {}
  var numobj2 = {}
  numobj1.cutter_specs = 'SUM'
  numobj1.pr = '计划数量'
  numobj2.cutter_specs = 'SUM'
  numobj2.pr = '实领数量'

  procelist.forEach(function(sp,index) {
     numobj1['col'+index] = 0;
     numobj2['col'+index] = 0;
  });

  for (var i=1;i<numlist.length; i++) {
    if(numlist[i].pr === '计划数量') {
      procelist.forEach(function(sp,index) {
        if (numlist[i]['col'+index] !== '') 
          numobj1['col'+index] = parseInt(numobj1['col'+index])+
            parseInt(numlist[i]['col'+index])
      });  
    } else {
        procelist.forEach(function(date,index) {
         if (numlist[i]['col'+index] !== '')
           numobj2['col'+index] = parseInt(numobj2['col'+index])+
             parseInt(numlist[i]['col'+index])
      });  
    }
  }; 
 numlist.push(numobj1);
 numlist.push(numobj2);
 console.log(JSON.stringify(numlist)); 
}
 function select(){
	 
var vm = new Vue({
  el: '#app',
  data: {
  	  numlist:[],
      columns:[],
      prolist: prolist,
      procelist:[],
  },   
  methods: {
     showdetail(list,proc_idx) {
       console.log(proc_idx);
       spceslist = [];
       jsonlist.forEach(function(item,index) {
        if (spceslist.indexOf(item.cutter_specs) === -1 && item.project_name === list) {
          spceslist.push(item.cutter_specs);
        }
       });
      var newarr =jsonlist.filter(function(pitem) {
       return pitem.project_name === list; 
      });
      procelist = []
      newarr.forEach(function(item,index) {
        if (procelist.indexOf(item.process_name) === -1) {
         procelist.push(item.process_name);
        };
      })
      numlist=[];
      numobj={};
      columns=[];
      numobj.cutter_specs = '';
      numobj.pr = '';
      procelist.forEach(function(proc,idx){  
     //console.log(proc)
       numobj['col'+idx] =proc;
       columns.push('col'+idx);
      });
      numlist.push(numobj)
      procelist.forEach(function(proc,index){
       spceslist.forEach(function(specs,idx){
         var marr = jsonlist.filter(function(item) {
           return item.process_name === proc && item.cutter_specs === specs && item.project_name === list;
         });
         //console.log(JSON.stringify(marr));   
         fillTable(marr)
       })
     })
     numlist=sortByKey(numlist,'cutter_specs');
     clcSum(procelist,numlist) //sum
      
     this.numlist=numlist;
     this.columns=columns; 
     var objlist = document.querySelectorAll('#proc');
     console.log(objlist.length)
     for (var i=0;i<objlist.length;i++) {
       if (i===proc_idx) {
         if (objlist[i].style.display == 'block')
           objlist[i].style.display = 'none';
         else objlist[i].style.display = 'block'
        }
       else objlist[i].style.display = 'none';
     };
    },
    init:init,
    outputexcel:function(){
        JSONToCSVConvertor(numlist,'项目用刀量',true);
      }
  },
  ready:function () { 
  	this.init()
  }
}) 
 }

 function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
     var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
     var CSV = '';    
     CSV += ReportTitle + '\r\n\n';
     if (ShowLabel) {
         var row = "";
         for (var index in arrData[0]) {
               //Now convert each value to string and comma-seprated
             if(index=="cutter_specs"){
            	 index="物料";
             }else if(index=="pr"){
            	 index="类型"
             }else if(index=="col0"){
            	 index="数量"
             }
              row += index + ',';
         }

         row = row.slice(0, -1);
         //append Label row with line break
 
         CSV += row + '\r\n';
     }
     
     //1st loop is to extract each row
     for (var i = 1; i < arrData.length; i++) {
         var row = "";
         //2nd loop will extract each column and convert it in string comma-seprated
         for (var index in arrData[i]) {
             row += '"' + arrData[i][index] + '",';
         }

         row.slice(0, row.length - 1);
         
         //add a line break after each row
         CSV += row + '\r\n';
     }

     if (CSV == '') {        
         alert("Invalid data");
         return;
     }   
     //Generate a file name
     var fileName = "msmkreport_";
     fileName += ReportTitle.replace(/ /g,"_");   
     //Initialize file format you want csv or xls
     var uri = 'data:text/csv;charset=utf-8,'+ encodeURIComponent(CSV);
     var link = document.createElement("a");    
     link.href = uri;
     link.style = "visibility:hidden";
     link.download = fileName + ".csv";
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
 }
</script>


</body>
</html>